package com.ruoyi.common.sms.service;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.sms.properties.AliyunSmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 阿里云短信工具类
 * @author lcj
 * @date 2025-06-03
 */
@Slf4j
@Component
public class AliyunSmsService {


    @Autowired
    private AliyunSmsProperties smsProperties;

    /**
     * 配置阿里云连接
     * @return Client
     */
    private Client createClient() throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID
                .setAccessKeyId(smsProperties.getAccessKey())
                // 配置 AccessKey Secret，
                .setAccessKeySecret(smsProperties.getSecretKey());
        // 配置 Endpoint。中国站使用dysmsapi.aliyuncs.com
        config.endpoint = smsProperties.getUrl();
        return new Client(config);
    }

    /**
     * 发送消息
     * @param phoneNumbers 手机号
     * @param param 参数
     */
    public boolean sendMessage(String phoneNumbers,String templateCode,String param){
        try {
            // 初始化请求客户端
            Client client = createClient();
            // 构造API请求对象，请替换请求参数值
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumbers)
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(templateCode)
                    .setTemplateParam(param); // TemplateParam为序列化后的JSON字符串。
            // 获取响应对象
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            log.info("短信返回参数:{}",JSON.toJSONString(sendSmsResponse));
            //成功
            return sendSmsResponse != null && sendSmsResponse.getBody() != null
                    && Objects.equals("OK", sendSmsResponse.getBody().getCode());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
